package com.learning.platform.controller;

import com.learning.platform.dto.ApiResponse;
import com.learning.platform.dto.CourseResponse;
import com.learning.platform.security.UserPrincipal;
import com.learning.platform.service.UserFavoriteService;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/v1/favorites")
public class UserFavoriteController {
    
    private final UserFavoriteService favoriteService;
    
    public UserFavoriteController(UserFavoriteService favoriteService) {
        this.favoriteService = favoriteService;
    }
    
    /**
     * 收藏课程
     */
    @PostMapping("/{courseId}")
    public ApiResponse<Void> addFavorite(@PathVariable Long courseId, Authentication auth) {
        UserPrincipal principal = (UserPrincipal) auth.getPrincipal();
        favoriteService.addFavorite(principal.getUserId(), courseId);
        return ApiResponse.success(null, "收藏成功");
    }
    
    /**
     * 取消收藏
     */
    @DeleteMapping("/{courseId}")
    public ApiResponse<Void> removeFavorite(@PathVariable Long courseId, Authentication auth) {
        UserPrincipal principal = (UserPrincipal) auth.getPrincipal();
        favoriteService.removeFavorite(principal.getUserId(), courseId);
        return ApiResponse.success(null, "取消收藏成功");
    }
    
    /**
     * 检查收藏状态
     */
    @GetMapping("/{courseId}/status")
    public ApiResponse<Boolean> checkFavoriteStatus(@PathVariable Long courseId, Authentication auth) {
        UserPrincipal principal = (UserPrincipal) auth.getPrincipal();
        boolean isFavorited = favoriteService.isFavorited(principal.getUserId(), courseId);
        return ApiResponse.success(isFavorited);
    }
    
    /**
     * 获取我的收藏列表
     */
    @GetMapping("/my")
    public ApiResponse<Page<CourseResponse>> getMyFavorites(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int pageSize,
            Authentication auth) {
        
        UserPrincipal principal = (UserPrincipal) auth.getPrincipal();
        Pageable pageable = PageRequest.of(page - 1, pageSize);
        Page<CourseResponse> favorites = favoriteService.getUserFavorites(principal.getUserId(), pageable);
        return ApiResponse.success(favorites);
    }
}

